package DMSXL._2023Before.ListNode_;

/*public class MyLinkedList_ {
    public static void main(String[] args) {
        MyLinkedList myLinkedList = new MyLinkedList();
        myLinkedList.addAtHead(1);
        myLinkedList.printlist();

        myLinkedList.addAtTail(3);
        myLinkedList.printlist();

        myLinkedList.addAtIndex(1, 2);    // 链表变为 1->2->3
        myLinkedList.printlist();

        System.out.println(myLinkedList.get(1));
        // 返回 2
        myLinkedList.deleteAtIndex(1);    // 现在，链表变为 1->3
        myLinkedList.printlist();

        System.out.println(myLinkedList.get(1));
    }
}
class MyLinkedList {
    ListNode head;
    int size = 0;
    public MyLinkedList() {
        head = new ListNode();
        head.next = null;
    }

    public int get(int index) {
        if(index < size){
            ListNode newhead = head;
            for (int i = 0; i <= index; i++) {
                newhead = newhead.next;
            }
            return newhead.val;
        }
        return -1;
    }

    public void addAtHead(int val) {
        ListNode node = new ListNode(val);
        node.next = head.next;
        head.next = node;
        size++;
    }

    public void addAtTail(int val) {
        ListNode node = new ListNode(val);
        ListNode newhead = head;
        while(newhead.next != null){
            newhead = newhead.next;
        }
        node.next = newhead.next;
        newhead.next = node;
        size++;
    }

    public void addAtIndex(int index, int val) {
        if(index < size){
            ListNode node = new ListNode(val);
            ListNode newhead = head;
            for (int i = 0; i < index; i++) {
                newhead = newhead.next;
            }
            node.next = newhead.next;
            newhead.next = node;
            size++;
        }

    }

    public void deleteAtIndex(int index) {
        if (index < size){
            ListNode newhead = head;
            for (int i = 0; i < index; i++) {
                newhead = newhead.next;
            }
            newhead.next = newhead.next.next;
            size--;
        }

    }

    public void printlist() {
        ListNode newhead = head;
        while(newhead.next != null){
            System.out.print(newhead.next.val + "  ");
            newhead = newhead.next;
        }
        System.out.println();
    }
}
*/